package com.jmebananas.input.action;

import com.jme.input.action.InputActionEvent;
import com.jme.input.action.KeyInputAction;
import com.jme.math.FastMath;
import com.jme.renderer.Camera;
import com.jme.system.DisplaySystem;

/**
 * KeyZoomAction
 * 
 * @author Glenn Powell
 * 
 */
public class KeyZoomAction extends KeyInputAction {

	private Camera camera;
	
	private float zoom;
	

	public KeyZoomAction(Camera camera, float speed) {
		this.camera = camera;
		this.speed = speed;
		
		int height = DisplaySystem.getDisplaySystem().getHeight();
		float frustumHeight = Math.abs(camera.getFrustumTop() - camera.getFrustumBottom());
		zoom = height / frustumHeight;
	}

	public void performAction(InputActionEvent evt) {
		if (camera.isParallelProjection()) {
			int width = DisplaySystem.getDisplaySystem().getWidth();
			int height = DisplaySystem.getDisplaySystem().getHeight();
			
			zoom *= FastMath.pow(2, evt.getTime() * speed);
			if (zoom <= FastMath.FLT_EPSILON)
				zoom = FastMath.FLT_EPSILON;
			
			float frustumWidth = width / zoom;
			float frustumHeight = height / zoom;
			float dWidth = (camera.getFrustumRight() - camera.getFrustumLeft()) - frustumWidth;
			float dHeight = (camera.getFrustumTop() - camera.getFrustumBottom()) - frustumHeight;
			if (frustumWidth > FastMath.FLT_EPSILON && frustumHeight > FastMath.FLT_EPSILON) {
				camera.getLocation().x += dWidth * 0.5f;
				camera.getLocation().y += dHeight * 0.5f;
				float frustumLeft = 0;
				float frustumTop = frustumHeight;
				float frustumRight = frustumWidth;
				float frustumBottom = 0;
				camera.setFrustumLeft(frustumLeft);
				camera.setFrustumTop(frustumTop);
				camera.setFrustumRight(frustumRight);
				camera.setFrustumBottom(frustumBottom);
				camera.update();
			}
		}
	}

}